<template>
  <yt-page title="现场处理措施">
    <yt-form>
      <yt-card title="基本信息">
        <yt-cell label="文书编号">
          <yt-input v-model="form.document_num" :clearable="false"></yt-input>
        </yt-cell>
        <yt-cell label="被检查企业" :value="enterpriseName"></yt-cell>
        <yt-cell label="检查日期">
          <yt-cell-time v-model="form.check_date"></yt-cell-time>
        </yt-cell>
        <yt-cell label="检查人员">
          <yt-cell-select v-model="form.check_person" :max="2" :list="userList" label="DisplayName" val="id"></yt-cell-select>
        </yt-cell>
        <yt-cell label="处理依据法规" labelWidth="100px" border="none">
          <yt-input v-model="form.dep_law" :clearable="false"></yt-input>
        </yt-cell>
      </yt-card>
      <yt-card @btn-click="goHidden" title="存在隐患" btn="添加隐患内容">
        <yt-cellSwipe v-for="(item, index) in form.troubles" :data="index" :items="items" :key="index">
          <p class="row">{{ index + 1 }}：{{ item }}</p>
        </yt-cellSwipe>
      </yt-card>
      <yt-card @btn-click="goContent" title="处理决定" btn="添处理内容">
        <yt-cellSwipe v-for="(item, index) in form.solutions" :data="index" :items="items2" :key="index">
          <p class="row">{{ index + 1 }}：{{ item }}</p>
        </yt-cellSwipe>
      </yt-card>
      <yt-btn v-if="!form.id" slot="btn" :loading="onSubmit" theme="blue" edge>保存</yt-btn>
      <yt-btn-group v-else slot="btn" edge>
        <yt-btn theme="white" :loading="onPreview" :loadingOption="{color: '#46baff'}">预览文书</yt-btn>
        <yt-btn theme="white" :loading="onSubmit" :loadingOption="{color: '#46baff'}">保存</yt-btn>
      </yt-btn-group>
    </yt-form>
  </yt-page>
</template>

<script>
import { EVENTS, BUS } from '@/store'
import { PointerToString, BuildPointer } from '@/common/utils/index.js'
import { commonApi } from '@/common/api/commonApi'
import { bridge } from '@/common/plugin/index.js'

export default {
  data() {
    return {
      form: {},
      userList: [],
      enterpriseName: '',
      items: [
        {
          type: 'red',
          text: '删除',
          confirmText: '确定删除',
          confirm: index => {
            this.form.troubles.splice(index, 1)
          }
        }
      ],
      items2: [
        {
          type: 'red',
          text: '删除',
          confirmText: '确定删除',
          confirm: index => {
            this.form.solutions.splice(index, 1)
          }
        }
      ]
    }
  },
  created() {
    BUS.$on(EVENTS.lawDisposalHidden, list => {
      this.form = { ...this.form, troubles: list }
    })
    BUS.$on(EVENTS.lawDisposalContent, list => {
      this.form = { ...this.form, solutions: list }
    })
  },
  methods: {
    async onPreview(loaded) {
      try {
        let word = await commonApi.runCloud('officeCopy', {
          code: 'D0001',
          data: this.$route.query.id
        })
        let { url } = await commonApi.runCloud('WordToPdf', { word })
        if (!url) {
          this.$Toast('文件转换失败，请尝试重新预览！', 'error')
          loaded()
          return
        }
        bridge.PreviewPdf({ title: '文件标题', url: url })
      } catch (e) {}
      loaded()
    },
    async onSubmit(loaded) {
      try {
        let { id, enterprise } = this.$route.query
        let form = { ...this.form, ent_id: enterprise, law_plan: id }
        form = BuildPointer(form, {
          check_person: 'aj_organization_personnel',
          ent_id: 'ent_enterprise',
          law_plan: 'law_plan'
        })
        await commonApi.save('law_site_disposal', form)
        this.$router.$back()
        this.$Toast('提交成功!', 'success')
      } catch (e) {
        this.$Toast('提交失败!', 'error')
      }
      loaded()
    },
    goHidden() {
      this.$router.$push({
        path: '/law/disposal/hidden',
        query: { data: this.form.troubles }
      })
    },
    goContent() {
      this.$router.$push({
        path: '/law/disposal/content',
        query: { data: this.form.solutions }
      })
    },
    async init() {
      this.id = this.$route.query.id
      let form = await commonApi.searchFirst('law_site_disposal', {
        equalTo: { law_plan: this.id },
        include: ['ent_id']
      })
      this.form = form ? PointerToString(form, ['check_person:array']) : {}
      if (this.form.document_num) return
      let { D0005 } = await commonApi.runCloud('lawGetDocumentNum', {
        year: new Date().getFullYear()
      })
      this.form = { ...this.form, document_num: D0005 }
    },
    async fetchData() {
      this.userList = await commonApi.search('aj_organization_personnel', {
        include: ['OrganizationIds'],
        matchesQuery: {
          OrganizationIds: commonApi.createQueryIncludeOptions(
            'sys_organizations',
            {
              equalTo: {
                Name: '安监局执法'
              }
            }
          )
        }
      })
    }
  },
  activated() {
    this.enterpriseName = this.$route.query.enterpriseName
    if (!this.$router.$isBack) {
      this.init()
      this.fetchData()
    }
  }
}
</script>

<style lang="stylus" scoped>
.row
  padding-left 10px
  line-height 36px
  font-size 14px
</style>
